package com.ruoyi.controller.jpjs.concrete;

import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.ArrayUtil;
import com.ruoyi.domain.jpjs.common.concrete.Concrete;
import com.ruoyi.domain.jpjs.common.concrete.ConcreteParam;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.service.jpjs.concrete.ConcreteService;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.util.concrete.ExportExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author C.fw
 * @explain 混凝土报表控制层
 * @since 2020/8/15 15:43
 */
@Controller
@RequestMapping("/concreteManage")
public class ConcreteController extends BaseController {

    private String prefix = "jpjs/concrete";

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private ConcreteService concreteService;

    /**
     * 混凝土报表菜单url:跳转首页面
     *
     * @return 首页面
     */
    @GetMapping()
    public String concreteManage() {
        return prefix + "/concreteManage";
    }

    /**
     * 初始化:获取概要列表
     *
     * @param map 前台封装参数
     * @return 分页list
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo selectConcreteList(@RequestParam Map<String, Object> map) {
        startPage();
        map.put("programName", map.get("programName").toString().trim().replaceAll(",", ""));
        // 获取当前登录人对应的项目权限
        getUserId(map);
        List<Concrete> list = concreteService.selectConcreteList(map);
        return getDataTable(list);
    }

    private void getUserId(@RequestParam Map<String, Object> map) {
        // 获取当前登录人对应的项目权限
        // 获取当前的用户信息
        SysUser currentUser = ShiroUtils.getSysUser();
        // 获取当前的用户ID
        Long userId = currentUser.getUserId();
        map.put("userId", userId);
    }

    /**
     * 初始化:获取树组件列表
     *
     * @return 树组件list
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData() {
        return concreteService.getProgramTree();
    }

    /**
     * 新增按钮:跳转新增页面
     *
     * @param mmp         modelAndView
     * @param companyId   工程公司ID
     * @param proId       项目ID
     * @param programName 项目名称
     * @return 新增页面
     */
    @GetMapping("/add")
    public String addProject(ModelMap mmp, String programName, String companyId, String proId) {
        Map<String, Object> map = new HashMap<>();
        map.put("companyId", companyId);
        map.put("proId", proId);
        mmp.put("buildingNumber", concreteService.selectBuildingNumberList(map));
        mmp.put("floorNumber", sysDictDataService.selectDictDataByType("floor_number"));
        mmp.put("companyId", companyId);
        mmp.put("programId", proId);
        mmp.put("programName", programName);
        return prefix + "/concreteAdd";
    }

    /**
     * 新增页面 > 保存按钮:保存报表数据
     *
     * @param concreteParam 混凝土报表封装实体类
     * @return 返回参数
     */
    @PostMapping("/save")
    @ResponseBody
    public AjaxResult save(ConcreteParam concreteParam) {
        List<Concrete> concreteList = concreteParam.getConcrete();
        for (Concrete concrete : concreteList) {
            concrete.setCheckPerson(ShiroUtils.getLoginName());
            concrete.setCompanyId(concreteParam.getCompanyId());
            concrete.setProgramId(concreteParam.getProgramId());
            // 校验:工程公司，项目名称，工程部位，结构部位，设计标号唯一性
//            List<Concrete> concretes = concreteService.checkConcreteUnique(concrete);
//            if (concretes.size() > 0) {
//                return new AjaxResult(AjaxResult.Type.WARN, MessageUtils.message("concrete.info.unique"));
//            }
        }
        return toAjax(concreteService.insertConcreteBatches(concreteList));
    }

    /**
     * 编辑按钮：跳转编辑页面
     *
     * @param mmp     modelAndView
     * @param checkId 主键
     * @return 编辑页面
     */
    @GetMapping("/editListView")
    public String editListView(ModelMap mmp, String checkId, String programName, String companyId, String programId) {
        Map<String, Object> map = new HashMap<>();
        map.put("companyId", companyId);
        map.put("proId", programId);
        mmp.put("buildingNumber", concreteService.selectBuildingNumberList(map));
        mmp.put("floorNumber", sysDictDataService.selectDictDataByType("floor_number"));
        mmp.put("checkId", checkId);
        mmp.put("programName", programName);
        return prefix + "/concreteEdit";
    }

    /**
     * 编辑页面:获取详细列表
     */
    @PostMapping("/detailListData")
    @ResponseBody
    public TableDataInfo detailListData(@RequestParam Map<String, Object> map) {
        startPage();
        List<Map<String, Object>> list = concreteService.selectConcreteDetailList(map);
        return getDataTable(list);
    }

    /**
     * 编辑页面 > 保存按钮:保存报表数据
     *
     * @param concreteParam 混凝土报表封装实体类
     * @return 响应结果
     */
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult edit(ConcreteParam concreteParam) {
        // Step1 参数准备
        List<Concrete> concreteList = concreteParam.getConcrete();
        Concrete concrete = concreteList.get(0);
        concrete.setCheckId(concreteParam.getCheckId());

        // Step2 校验:工程公司，项目名称，工程部位，结构部位，设计标号唯一性
//        List<Concrete> concretes = concreteService.checkConcreteUnique(concrete);
//        if (concretes.size() > 1) {
//            return new AjaxResult(AjaxResult.Type.WARN, MessageUtils.message("concrete.info.unique"));
//        }

        // Step3 更新并响应结果
        return toAjax(concreteService.updateConcreteById(concrete));
    }

    /**
     * 删除按钮
     *
     * @param ids 传入id
     * @return 响应结果
     */
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            return toAjax(concreteService.deleteUserBycheckId(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 导出按钮
     *
     * @param map 前端封装参数
     * @return 响应结果
     */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(@RequestParam Map<String, Object> map) {

        // Step1 获取需要导出的数据
        List<Concrete> list = concreteService.selectConcreteList(map);
        String filePath = Global.getDownloadPath() + "混凝土强度试验检测统计表.xls";
        try {
            if (!ArrayUtil.isEmpty(list)) {
                // Step3.2 导出多个项目
                FileOutputStream fout = new FileOutputStream(filePath);
                new ExportExcel().getValue(list, fout);
                fout.close();
            }
        } catch (Exception e) {
            error(e.getMessage());
        }
        return AjaxResult.success(0);
    }

    /**
     * 判断导出数据中是否为一个项目
     *
     * @param list 需要导出的数据
     * @param flag 标识
     * @return 响应标识
     */
    private Boolean checkProgramUnique(List<Concrete> list, Boolean flag) {
        for (int i = 0; i < list.size(); i++) {
            String companyName = list.get(0).getCompanyName();
            String programName = list.get(0).getProgramName();
            if (!(list.get(i).getCompanyName().toString().trim().equals(companyName.trim()))
                    || !(list.get(i).getProgramName().toString().trim().equals(programName.trim()))) {
                flag = false;
            }
        }
        return flag;
    }

    /**
     * 首页面初始化:联想项目名称
     *
     * @return
     */
    @GetMapping("/collection")
    @ResponseBody
    public AjaxResult collection() {
        List<Map<String, Object>> list = concreteService.getProgramNameList();
        if (!ArrayUtil.isEmpty(list)) {
            String[] array = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                array[i] = list.get(i).get("name").toString();
            }
            AjaxResult ajax = new AjaxResult();
            ajax.put("value", array);
            return ajax;
        }
        AjaxResult ajax = new AjaxResult();
        return ajax;
    }
}
